﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;

using YLClient.Util;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using YLPublicService.TransferModel;

namespace YLClient.Froms
{
    /// <summary>
    /// Interaction logic for NewItem.xaml
    /// </summary>
    public partial class NewItem : Window
    {
        ClientAdapter client;
        List<string> errorFiles;
        public NewItem()
        {
            InitializeComponent();

            initialUI();

            errorFiles = new List<string>();
            client = new ClientAdapter(false);
            client.OnTransfefMoveNext += new TransfefMoveNext(client_OnTransfefMoveNext);
            client.OnTransferError += new TransferFileError(client_OnTransferError);
        }

        void client_OnTransferError(string fileName)
        {
            errorFiles.Add(fileName);
        }

        void client_OnTransfefMoveNext(string preFileName, double precent)
        {
            //使用Dispatcher实现异步更新控件
            Action<double> update = v => progressBar.Value = v;
            Dispatcher.Invoke(
                update
                , DispatcherPriority.ApplicationIdle
                , precent
            );
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //timePick.Time = DateTime.Now;

        }

        private IEnumerable<T> singleToIEnumerable<T>(T o)
        {
            yield return o;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            var ret = MessageBox.Show("是否退出？", "帮助", MessageBoxButton.YesNo);
            if (ret == MessageBoxResult.Yes)
            {
                this.Close();
            }
        }

        public string[] GetUploadFiles()
        {
            return lstFiles.Items.Cast<UserControls.TemplateControls.RequireAttachment>()
                .Select(item => item.FilePath).ToArray();
        }

        //private void btnAdd_Click(object sender, RoutedEventArgs e)
        //{


        //#region UI控制
        //btnAdd.IsEnabled = false;
        //#endregion

        //#region 数据初始化
        //errorFiles.Clear();
        //#endregion

        //#region 验证数据完整性
        //if (false == checkAllValue()) //判断信息是否填写完毕
        //{
        //    MessageBox.Show("请完善信息！", "提示");
        //    return;
        //}
        //#endregion

        ////将要上传的文件名字列表
        //var files = GetUploadFiles();

        //#region 初始化WorkItem
        //var t = tm.templates[cmbTemplateName.SelectedIndex];
        //initialTemplateInstance(t);
        //WorkItem item = BuildWorkItem(t);
        //#endregion

        //txtbStatus.Text = "开始压缩图片......";
        //progressBar.Value = 100;

        ////压缩图片：
        //Task<string> imgTask = new Task<string>(() =>
        //{
        //    #region 压缩图片
        //    ImageProcessHelper imgProcesser = new ImageProcessHelper();
        //    return imgProcesser.CompressImages(files);//耗时操作
        //    #endregion
        //});
        //imgTask.ContinueWith(
        //    imgt =>
        //    {

        //    }
        //, TaskContinuationOptions.OnlyOnFaulted);
        ////压缩后：
        //imgTask.ContinueWith(
        //    imgt =>
        //    {
        //        #region 上传照片
        //        txtbStatus.Text = "图片压缩完成,开始上传图片......";
        //        progressBar.Value = 0;
        //        var cmpFilesDir = imgTask.Result;
        //        var compressFiles = Common.getDirFiles(cmpFilesDir);

        //        var serviceClient = YLServiceClient.ServiceClient.GetServiceClient();
        //        serviceClient.AddWorkItem(item);

        //        if (!client.UploadWorkItemFiles(item, compressFiles, 0.3))//上传工作项，数据库上传和ftp上传
        //        {
        //            MessageBox.Show("上传过程出错！", "错误");
        //        }
        //        else
        //        {
        //            //设置按钮的content为空就是的文件列表清空。因为他们之间存在绑定

        //            //  lstFileNames.UpdateLayout();
        //            if (errorFiles.Count > 0)
        //            {
        //                MessageBox.Show("传输过程中存在失败文件，请再次上传...", "提示");
        //                // errorFiles.ToList().ForEach(file => lstFileNames.Items.Add(file));
        //            }
        //        }
        //        //删除传输成功的临时文件
        //        var successTransferFiles = compressFiles.Except(errorFiles);
        //        deleteTempFiles(successTransferFiles);
        //        //一切正常，提示成功然后关闭
        //        txtbStatus.Text = "准备就绪";
        //        btnAdd.Content = "继续上传";
        //        progressBar.Value = 0;
        //        #endregion
        //    },
        //   TaskScheduler.FromCurrentSynchronizationContext() //因为上面方法中使用到了U上的控件.如果使用dispatcher也是可行的
        //);
        //imgTask.Start();

        //btnAdd.IsEnabled = true;
        //}



        private void initialTemplateInstance(TemplateItem t)
        {
            t.mTemplateDetial.mRequireValues.mItem.Clear();
            foreach (dynamic item in lstRequireValues.Items)
            {
                t.mTemplateDetial.mRequireValues.mItem.Add(item.Item);
            }
            t.mTemplateDetial.mRequireAttchments.mItem.Clear();
            foreach (dynamic item in lstFiles.Items)
            {
                t.mTemplateDetial.mRequireAttchments.mItem.Add(item.Item);
            }
        }

        private string getRequireValuesXml()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in lstRequireValues.Items)
            {
                sb.Append(item.ToString());
            }
            return sb.ToString();
        }
        private string getRequireAttachmentXml()
        {
            throw new NotImplementedException();
        }

    }
}
